package gw.com.android.ui.me;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.AppContances;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.SelectPhotoDialog;
import gw.com.android.ui.views.GlideCircleTransform;
import gw.com.android.utils.ImageUtil;
import gw.com.android.utils.PackStatis;
import www.com.library.app.Logger;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.util.PermissionUtil;
import www.com.library.view.BtnClickListener;

/**
 * @author jett
 * @since 2018-03-02.
 */
public class ProfileActivity extends BaseActivity {

    private final String TAG = "ProfileActivity";
    private final int REQUEST_NICKNAME = 16;
    private final int REQUEST_CROP = 17;

    @BindView(R.id.profile_avatar)
    ImageView ivIcon;
    @BindView(R.id.profile_nickname)
    TextView tvNickname;
    @BindView(R.id.profile_phone)
    TextView tvPhone;
    @BindView(R.id.profile_gender_male)
    ViewGroup vgMale;
    @BindView(R.id.profile_cb_male)
    ImageView cbMale;
    @BindView(R.id.profile_gender_female)
    ViewGroup vgFemale;
    @BindView(R.id.profile_cb_female)
    ImageView cbFemale;

    private ProfileData mProfile;
    private ProfileRequest mRequest;
    private String takePhotoPath;
    private PermissionUtil mAccessCameraPermission;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_profile;
    }

    @Override
    protected void initLayoutView() {
        mTitleBar.setAppTitle(R.string.profile_title);
        mTitleBar.setRightIcon(R.mipmap.a_nav_service_b);
        mTitleBar.setBtnClickListener(new BtnClickListener() {
            @Override
            public void onBtnClick(int viewID) {
                if (viewID == R.id.title_left_icon) {
                    finish();
                } else if (viewID == R.id.title_right_icon) {
                    PackStatis.getToService("clickService1", "Me", null, null);
                    ConfigSettingDeal mDeal = new ConfigSettingDeal();
                    if (ConfigUtil.instance().customerFunction() == 2) {
                        mDeal.openContact(ProfileActivity.this, ConfigType.QUOTE_CONTACT_TAG);
                    } else {
                        mDeal.openQQ(ProfileActivity.this, "APP个人详情");
                    }
                }
            }
        });
    }

    @Override
    protected void initViewData() {
        mProfile = getProfileRequest().fetchLocal();
        if (mProfile != null) {
            refreshUi(mProfile);
        }
        getFromNet();
    }

    private void getFromNet() {
        PhoneNumber.getInstance().acquireAsync(new PhoneNumber.OnPhoneListener() {
            @Override
            public void onSuccess(String num) {
                Logger.i(TAG, "get phone number success.");
                requestUserInfo(num);
            }

            @Override
            public void onFailure() {
                Logger.i(TAG, "request phone number failed.");
                if (mProfile != null && TextUtils.isEmpty(mProfile.mobilePhone)) {
                    Logger.i(TAG, "get cached phone number,request user info now.");
                    requestUserInfo(mProfile.mobilePhone);
                }
            }
        });
    }

    private void requestUserInfo(String num) {
        getProfileRequest().getUserInfo(num, new HttpCallback<ProfileData>() {
            @Override
            public void onSuccess(ProfileData result) {
                refreshUi(result);
            }

            @Override
            public void onFailure(Exception e) {
                Logger.e(TAG, e);
            }
        });
    }

    private void refreshUi(ProfileData profile) {
        if (profile == null) {
            return;
        }
        this.mProfile = profile;
        if (!TextUtils.isEmpty(profile.avatar)) {
            Glide.with(this).load(profile.avatar)
                    .placeholder(profile.isFemale() ? R.mipmap.a_profiles_f : R.mipmap.a_show_profiles)
                    .transform(new GlideCircleTransform(getApplicationContext())).into(ivIcon);
        }
        refreshNickname(profile.nickname);
        tvPhone.setText(encryptPhoneNum(profile.mobilePhone));
        refreshGender(profile.isFemale());
    }

    private void refreshNickname(String nickname) {
        if (TextUtils.isEmpty(nickname)) {
            tvNickname.setTextColor(getResources().getColor(R.color.color_k));
            tvNickname.setText(R.string.profile_not_set);
        } else {
            tvNickname.setTextColor(getResources().getColor(R.color.color_u));
            tvNickname.setText(nickname);
        }
    }

    private void refreshGender(boolean isFemale) {
        if (isFemale) {
            cbMale.setImageResource(R.mipmap.a_login_normal);
            cbFemale.setImageResource(R.mipmap.a_login_checked);
        } else {
            cbMale.setImageResource(R.mipmap.a_login_checked);
            cbFemale.setImageResource(R.mipmap.a_login_normal);
        }
        if (mProfile == null || TextUtils.isEmpty(mProfile.avatar)) {
            ivIcon.setImageResource(isFemale ? R.mipmap.a_profiles_f : R.mipmap.a_show_profiles);
        }
    }

    private String encryptPhoneNum(String num) {
        if (TextUtils.isEmpty(num)) {
            return num;
        }
        return num.replaceAll("^(.{3}).*(.{4})$", "$1****$2");
    }

    @OnClick({R.id.profile_avatar, R.id.profile_avatar_hint})
    void onAvatar(View view) {
        PackStatis.getToService("clickPortrait", "Me", null, null);
        new SelectPhotoDialog(this).hideTitle().selectListener(new SelectPhotoDialog.OnSelectListener() {
            @Override
            public void onAlbum(SelectPhotoDialog dialog, View view) {
                album();
            }

            @Override
            public void onCamera(SelectPhotoDialog dialog, View view) {
                requestCameraPermission();
            }
        }).show();
    }

    @OnClick(R.id.profile_nickname_container)
    void onNickname(View view) {
        PackStatis.getToService("clickNickname", "Me", null, null);
        Intent intent = new Intent(this, NicknameActivity.class);
        if (mProfile != null) {
            intent.putExtra(NicknameActivity.NAME, mProfile.nickname);
        }
        startActivityForResult(intent, REQUEST_NICKNAME);
    }

    @OnClick(R.id.profile_phone_container)
    void onPhoneNumber(View view) {
        new ToastPopWindow(this, getString(R.string.profile_phone_modify)).show();
    }

    @OnClick(R.id.profile_gender_male)
    void onMale(View view) {
        PackStatis.getToService("clickSex", "Me", null, null);
        if (mProfile == null || !mProfile.isFemale()) {
            return;
        }
        setGender("male");
    }

    @OnClick(R.id.profile_gender_container)
    void onFemale(View view) {
        PackStatis.getToService("clickSex", "Me", null, null);
        if (mProfile == null || mProfile.isFemale()) {
            return;
        }
        setGender("female");
    }

    private void setGender(String gender) {
        String num = PhoneNumber.getInstance().get();
        if (TextUtils.isEmpty(num)) {
            new ToastPopWindow(getApplicationContext(), getString(R.string.profile_modify_failed)).show();
            return;
        }
        showLoading();
        getProfileRequest().modifyGender(num, gender, new HttpCallback<String>() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                new ToastPopWindow(getApplicationContext(), getString(R.string.profile_modify_success)).show();
                if (mProfile != null) {
                    mProfile.gender = result;
                    refreshGender(mProfile.isFemale());
                }
            }

            @Override
            public void onFailure(Exception e) {
                Logger.e(TAG, e);
                hideLoading();
                new ToastPopWindow(getApplicationContext(), getString(R.string.profile_modify_failed)).show();
            }
        });
    }

    private void uploadAvatar(final String path) {
        if (mProfile == null || TextUtils.isEmpty(mProfile.mobilePhone)) {
            return;
        }
        showLoading();
        getProfileRequest().uploadAvatar(path, mProfile.mobilePhone, new HttpCallback<String>() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                if (mProfile != null) {
                    mProfile.avatar = result;
                }
                new ToastPopWindow(getApplicationContext(), getString(R.string.profile_modify_success)).show();
                Glide.with(ProfileActivity.this).load(path).transform(new GlideCircleTransform(getApplicationContext())).into(ivIcon);
            }

            @Override
            public void onFailure(Exception e) {
                Logger.e(TAG, e);
                hideLoading();
                new ToastPopWindow(getApplicationContext(), getString(R.string.profile_modify_failed)).show();
            }
        });
    }

    private void album() {
        try {
            Intent mSourceIntent = ImageUtil.choosePicture();
            startActivityForResult(mSourceIntent, AppContances.REQUEST_CODE_PICK_IMAGE);
        } catch (Exception ignore) {
        }
    }

    private void requestCameraPermission() {
        mAccessCameraPermission = new PermissionUtil();
        mAccessCameraPermission.requestPermission(this, Manifest.permission.CAMERA, AppContances.REQUEST_PERMISSION_ACCESS_CAMERA, new PermissionUtil.OnRequestPermissionResult() {
            @Override
            public void onGranted() {
                launchCamera();
            }

            @Override
            public void onRefused() {
            }
        });
    }

    private void launchCamera() {
        try {
            takePhotoPath = ImageUtil.getNewPhotoPath();
            Intent mSourceIntent = ImageUtil.takeBigPicture(this, takePhotoPath);
            startActivityForResult(mSourceIntent, AppContances.REQUEST_CODE_IMAGE_CAPTURE);
        } catch (Exception ignore) {
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mAccessCameraPermission != null) {
            mAccessCameraPermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_NICKNAME && resultCode == RESULT_OK && data != null) {
            String nickname = data.getStringExtra(NicknameActivity.NAME);
            if (mProfile != null) {
                mProfile.nickname = nickname;
            }
            refreshNickname(nickname);
            return;
        }
        if (requestCode == REQUEST_CROP && resultCode == RESULT_OK && data != null) {
            String path = data.getStringExtra("path");
            uploadAvatar(path);
            return;
        }
        switch (requestCode) {
            case AppContances.REQUEST_CODE_IMAGE_CAPTURE:
                launchCrop(takePhotoPath);
                takePhotoPath = null;
                break;
            case AppContances.REQUEST_CODE_PICK_IMAGE:
                String path = ImageUtil.retrievePath(this, null, data);
                launchCrop(path);
                break;
            default:
                break;
        }
    }

    private void launchCrop(String path) {
        startActivityForResult(new Intent(getApplicationContext(), CropActivity.class).putExtra("path", path), REQUEST_CROP);
    }

    private ProfileRequest getProfileRequest() {
        if (mRequest == null) {
            mRequest = new ProfileRequest();
        }
        return mRequest;
    }

    @Override
    protected void onDestroy() {
        getProfileRequest().cache2Local(mProfile);
        super.onDestroy();
    }

}
